import 'dart:io';

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/router_gen/router_gen_providers.dart';
import 'package:finance_app/src/widgets/bottom_sheet/photo_preview_bottom_sheet.dart';
import 'package:finance_app/src/widgets/style/image_style.dart';
import 'package:flutter/material.dart';
import 'package:photo_manager/photo_manager.dart';

import 'default_bottom_sheet.dart';

/// 添加附件
///
/// 返回对应的文件路径
showAttachmentsBottomSheet(BuildContext context,
    {String title, String attachName}) async {
  final result = await showDefaultBottomSheet(
    context,
    bottomMargin: 0,
    child: AttachmentsBottomSheet(
      attachName: attachName,
    ),
    title: title ?? S.current.attachments,
    isScrollControlled: true,
  );
  return result;
}

class AttachmentsBottomSheet extends StatefulWidget {
  final String attachName;

  const AttachmentsBottomSheet({Key key, this.attachName}) : super(key: key);

  @override
  _AttachmentsBottomSheetState createState() => _AttachmentsBottomSheetState();
}

class _AttachmentsBottomSheetState extends State<AttachmentsBottomSheet> {
  List<AssetEntity> assetList = [];

  @override
  void initState() {
    super.initState();
    _loadData();
  }

  void onPhotoLibrary() async {
    final path =
        await Routes.navigateTo(RouterGenProviders.selectPhotoPage, params: {
      'isSelect': true,
    });
    if (path != null) {
      onSelectFile(File(path), isFromPhotoLibrary: true, isChooseAgain: true);
    }
  }

  void onFiles() {}

  void onNavCamera() async {
    final path = await Routes.navigateTo(RouterGenProviders.ocrCameraPage,
        params: {'isSelect': true, 'activeOCR': false});
    if (path != null && path is String) {
      onSelectFile(File(path), isFromCamera: true);
    }
  }

  void onSelectFile(File data,
      {bool isFromCamera = false,
      bool isChooseAgain = false,
      bool isFromPhotoLibrary = false}) {
    showPhotoPreviewBottomSheet(context, data, null,
        attachName: widget.attachName,
        chooseAgainText: S.current.choose_again,
        onChooseAgain: isChooseAgain == true
            ? () async {
                if (isFromPhotoLibrary == true) {
                  final path = await Routes.navigateTo(
                      RouterGenProviders.selectPhotoPage,
                      params: {
                        'isSelect': true,
                      });
                  if (path != null) {
                    //这里是退出当前bottom
                    Navigator.of(context)..pop(path);
                    onSelectFile(File(path));
                  }
                } else {
                  Navigator.of(context).pop();
                }
              }
            : null,
        onChoosePhotoLibrary: isFromCamera == false &&
                isChooseAgain == false &&
                isFromPhotoLibrary == false
            ? () async {
                final path = await Routes.navigateTo(
                    RouterGenProviders.selectPhotoPage,
                    params: {
                      'isSelect': true,
                    });
                if (path != null) {
                  //这里是退出当前bottom
                  Navigator.of(context)..pop(path);
                  onSelectFile(File(path));
                }
              }
            : null, onAttach: () {
      //这里是退出当前bottom
      Navigator.of(context)..pop()..pop(data.path);
    }, onCrop: () async {
      final result = await Routes.navigateTo(RouterGenProviders.editPhotoPage,
          params: {
            'filepath': data.path,
            'isFromPhoto': true,
          },
          replace: true);
      if (result != null) {
        onSelectFile(File(result));
      }
    },
        onRetakePhoto: isFromCamera == true
            ? () {
                Navigator.of(context).pop();
                onNavCamera();
              }
            : null);
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
          margin: EdgeInsets.symmetric(vertical: 17),
          height: getDp(85),
          child: ListView.builder(
            scrollDirection: Axis.horizontal,
            itemBuilder: _buildItems,
            itemCount: assetList.length + 1,
          ),
        ),
        // SizedBox(
        //   height: getDp(17),
        // ),
        PressedOpacityButton(
          onPressed: onPhotoLibrary,
          child: Container(
            height: getDp(62),
            decoration: BoxDecoration(
                border: Border(
              top: BorderSide(color: aceGrayColor, width: getDp(0.5)),
            )),
            alignment: Alignment.center,
            child: Text(
              S.current.photo_library,
              style: TextStyle(
                color: aceBlueColor,
                fontSize: getSp(16),
                fontWeight: FontWeight.w700,
                height: 14 / 16,
              ),
            ),
          ),
        ),
        // PressedOpacityButton(
        //   onPressed: onFiles,
        //   child: Container(
        //     height: getDp(62),
        //     decoration: BoxDecoration(
        //         border: Border(
        //       top: BorderSide(color: aceGrayColor, width: getDp(0.5)),
        //     )),
        //     alignment: Alignment.center,
        //     child: Text(
        //       'Files',
        //       style: TextStyle(
        //         color: aceBlueColor,
        //         fontSize: getSp(16),
        //         fontWeight: FontWeight.w700,
        //         height: 14 / 16,
        //       ),
        //     ),
        //   ),
        // ),
      ],
    );
  }

  void _loadData() async {
    if (await PhotoManager.requestPermission()) {
      final assetPathGroup = await PhotoManager.getAssetPathList(
          onlyAll: true, type: RequestType.image);
      assetList = await assetPathGroup.first.assetList;
      Future.forEach(assetList, (asset) async {
        if (await asset.exists == false ||
            await asset.isLocallyAvailable == false) {
          assetList.remove(asset);
        }
      });
      setState(() {});
    } else {
      // Navigator.of(context).pop();
    }
  }

  Widget _buildItems(BuildContext context, int index) {
    if (index == 0) {
      return _buildCameraButton();
    }
    int _index = index - 1;
    final asset = assetList[_index];

    return Container(
      margin: EdgeInsets.symmetric(horizontal: getDp(12.5)),
      width: getDp(85),
      height: getDp(85),
      child: FutureBuilder(future: asset.file, builder: _buildImage),
    );
  }

  Widget _buildImage(BuildContext context, AsyncSnapshot<File> snapshot) {
    return snapshot.hasData
        ? PressedOpacityButton(
            onPressed: () => onSelectFile(snapshot.data, isChooseAgain: true),
            child: Material(
              clipBehavior: Clip.hardEdge,
              borderRadius: BorderRadius.circular(getDp(5)),
              child: Image.file(
                snapshot.data,
                fit: BoxFit.cover,
                frameBuilder: ImageStyle.fadeInFrame,
              ),
            ),
          )
        : Container(
            decoration: BoxDecoration(
              color: aceWhiteGreyColor,
              borderRadius: BorderRadius.circular(getDp(5)),
            ),
          );
  }

  Widget _buildCameraButton() {
    return PressedOpacityButton(
      onPressed: onNavCamera,
      child: Container(
        width: getDp(85),
        height: getDp(85),
        margin: EdgeInsets.symmetric(horizontal: getDp(12.5)),
        decoration: BoxDecoration(
          color: aceBlackColor,
          borderRadius: BorderRadius.circular(getDp(5)),
        ),
        alignment: Alignment.center,
        child: Icon(
          Icons.camera_alt,
          size: getDp(22),
          color: Colors.white,
        ),
      ),
    );
  }
}
